package com.wtwd.campus.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author xsansan
 * @date 2019年4月1日
 * @description
 */
public class ExcelUtils {

	public static boolean isExcel2003(String fileName) {
		return fileName.matches("^.+\\.(?i)(xls)$");
	}

	private static boolean isExcel2007(String fileName) {
		return fileName.matches("^.+\\.(?i)(xlsx)$");
	}

	/**
	 * 验证EXCEL文件
	 * @param  fileName fileName
	 * @return boolean
	 */
	public static boolean validateExcel(String fileName) {
		return fileName != null && (isExcel2003(fileName) || isExcel2007(fileName));
	}

    /**
     * 创建Sheet单元
     * @param file file
     * @return Sheet
     * @throws Exception e
     */
    public static Sheet createSheet(MultipartFile file) throws Exception {
        if (!ExcelUtils.validateExcel(file.getOriginalFilename())) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = ExcelUtils.isExcel2003(file.getOriginalFilename());
        InputStream is = file.getInputStream();
        // 根据版本选择创建Workbook的方式
        Workbook workbook = isExcel2003 ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
        // 得到第一个shell
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            throw new Exception("第一个shell不能为空");
        }
        return sheet;
    }


}
